package com.sydsen.imager.painter;

import com.sydsen.imager.elements.Element;
import com.sydsen.imager.elements.Image;
import com.sydsen.imager.elements.Shape;
import com.sydsen.imager.elements.Text;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @Auther: syh
 * @Date: 2021/11/1
 * @Description:
 */
public class PainterFactory {

    static final Map<Class<? extends Element>, IPainter<? extends Element>> painterMap =
            new HashMap<>();

    public static <T extends Element<T>> IPainter<T> getPainter(Element t) {
        IPainter<T>  painter = (IPainter<T>)painterMap.get(t.getClass());
        if (painter == null) {
            painter = (IPainter<T>) PAINTER.of(t.getClass()).get();
            painterMap.put(t.getClass(), painter);
        }

        return painter;
    }


    private enum PAINTER {
        TEXT(Text.class, TextPainter::new),
        IMAGE(Image.class, ImagePainter::new),
        SHAPE(Shape.class, ShapePainter::new);

        private Class<? extends Element> clazz;
        private Supplier<IPainter<? extends Element>> supplier;

        PAINTER(Class<? extends Element> clazz, Supplier<IPainter<? extends Element>> supplier) {
            this.clazz = clazz;
            this.supplier = supplier;
        }

        public static Supplier<IPainter<? extends Element>> of(Class<? extends Element> clazz) {
            for (PAINTER value : PAINTER.values()) {
                if (value.clazz.getName().equals(clazz.getName())) {
                    return value.supplier;
                }
            }
            throw new UnsupportedOperationException("不知道的painter类型");
        }
    }
}
